﻿using Nova_Common.Extend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using WMS_Api.Models;

namespace WMS_Api.App_Start
{
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                var message = string.Empty;
                var num = 0;
                foreach (var item in actionContext.ModelState.Values)
                {
                    if (!item.Errors[0].ErrorMessage.IsEmpty())
                    {
                        num++;
                        message += num + "：" + item.Errors[0].ErrorMessage + "；";
                    }

                }
                MesApiResult resp = new MesApiResult
                {
                    code = 1,
                    msg = message
                };

                int count = actionContext.ModelState.Values.First().Errors.Count;
                if (count > 1)
                {
                    resp = new MesApiResult
                    {
                        code = 1,
                        msg = actionContext.ModelState.Values.Last().Errors.Last().ErrorMessage
                    };
                }
                actionContext.Response = actionContext.Request.CreateResponse(resp);
            }

            base.OnActionExecuting(actionContext);
        }
    }
}